package cnm.red5;

import java.io.File;
import java.io.IOException;

import cnm.storage.StorageService;

import org.red5.server.api.IScope;
import org.red5.server.api.stream.IStreamFilenameGenerator;
import org.springframework.core.io.Resource;

public class CnmStreamFilenameGenerator implements IStreamFilenameGenerator {
	private StorageService storageService;
	private IScope scope;
	private boolean useAbsolutePath = true;

	public String generateFilename(IScope scope, String name,
			GenerationType type) {		
		return generateFilename(scope, name, "", type);
	}

	public String generateFilename(IScope scope, String name, String extension,
			GenerationType type) {
		return getRoot() + File.separator + name + extension;
	}

	public boolean resolvesToAbsolutePath() {
		return useAbsolutePath;
	}
	
	public void setUseAbsolutePath(boolean useAbsolutePath) {
		this.useAbsolutePath = useAbsolutePath;
	}

	public void setScope(IScope scope) {
		this.scope = scope;
	}

	public void setStorageService(StorageService storageService) {
		this.storageService = storageService;
	}
	
	public String getRoot() {
		return storageService.getRepoDir() + File.separator + "audio";
	}

	public void init() throws IOException {
		if (useAbsolutePath) {
			File rootDir = new File(getRoot());
			if (!rootDir.exists()) {
				rootDir.mkdirs();
			}
		} else {
			Resource rootRes = scope.getContext().getResource(getRoot());
			if (!rootRes.exists()) {
				rootRes.getFile().mkdirs();
			} else {
				File rootDir = rootRes.getFile();
				if (!rootDir.isDirectory()) {
					throw new IOException(getRoot() + " should be a directory!");
				}
			}
		}
	}
}
